package cn.wangzg.course0902.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.session.MediaSession;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

import java.util.ArrayList;

import cn.wangzg.course0902.MainActivity;
import cn.wangzg.course0902.Music;
import cn.wangzg.course0902.MyApp;
import cn.wangzg.course0902.R;
import cn.wangzg.course0902.util.MusicUtil;
import cn.wangzg.course0902.util.NotificationUtils;

public class PlayService extends Service {
    private static final String CHANNEL_ID = "musicplay";
    private MediaPlayer player; // 定义多媒体对象
    private int curPos;//记录当前播放位置
    private ArrayList<Music> musics;//播放列表
    private Music music;
    //通知管理器，发送通知
    private NotificationManager manager ;
    private int CommandPlay = 1;
    private int CommandPause = 2;
    private int CommandNext = 3;
    private int CommandClose = 4;
    private String channelId="music";


    public PlayService() {
        player = new MediaPlayer();
    }

    @Override
    public void onCreate() {
        //实例化通知管理器
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //8.0之后的变化，添加通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(channelId, "MyMusic", importance);
            //设置震动声音等
            channel.setVibrationPattern(new long[]{0,1300,500,1700});
            manager.createNotificationChannel(channel);
        }
        super.onCreate();
    }

    public void setMusics(ArrayList<Music> musics) {
        this.musics = musics;
    }

    public class PlayBinder extends Binder {
        public PlayService getPlayService() {
            return PlayService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new PlayBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //可以通过intent携带的参数，来控制音乐的播放
        int action = intent.getIntExtra("command", 0);
        //Toast.makeText(this, "action:" + action, Toast.LENGTH_SHORT).show();
        switch (action) {
            case 1:
                pause();
                break;
            case 2:
                start();
                break;
            case 3:
                start();
                break;
            case 4:
                next();
                break;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    //---------------------歌曲播放控制部分 开始---------------------------------------
    //播放第pos首歌曲
    public void play(int pos) {
        try {
            player.reset(); //重置多媒体
            music = musics.get(pos);//得到当前播放音乐的路径
            // 指定参数为音频文件
            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
            player.setDataSource(music.getUrl());//为多媒体对象设置播放路径
            player.prepare();//准备播放
            player.start();//开始播放
            //setOnCompletionListener 当当前多媒体对象播放完成时发生的事件
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer arg0) {
                    next();//如果当前歌曲播放完毕,自动播放下一首.
                }
            });
            curPos = pos;
            sendCustomerNotification(CommandPlay,music);
//            NotificationUtils notificationUtils = new NotificationUtils(this, 0,
//                    "musicplay", R.mipmap.music, "标题", "内容");
//            notificationUtils.notified();
//            iv_play.setSelected(true);
//            //歌曲发生变化，需要更新歌名、艺术家和专辑图片
//            tv_title.setText(music.getTitle());
//            tv_artist.setText(music.getArtist_name());
//            Bitmap bm = MusicUtil.getAlbumArt(resolver, music.getAlbum_id());
//            if(bm!=null) {
//                iv_music.setImageBitmap(bm);
//            }
        } catch (Exception e) {
            Log.v("------MusicService", e.getMessage());
        }
    }

    //暂停后，点击播放，继续播放
    public void start() {
        int position = getCurrentProgress();
        player.seekTo(position);//设置当前MediaPlayer的播放位置，单位是毫秒。
        try {
            player.prepare();//  同步的方式装载流媒体文件。
        } catch (Exception e) {
            e.printStackTrace();
        }
        player.start();
        sendCustomerNotification(CommandPlay,music);
        //iv_play.setSelected(true);
    }

    // 获取当前进度
    public int getCurrentProgress() {
        assert player != null;
        if (player != null & player.isPlaying()) {
            return player.getCurrentPosition();
        } else if (player != null & (!player.isPlaying())) {
            return player.getCurrentPosition();
        }
        return 0;
    }

    public int getCurPos() {
        return curPos;
    }

    public void next() {
        curPos = curPos == musics.size() - 1 ? 0 : curPos + 1;
        play(curPos);
    }


    // 暂停播放
    public void pause() {
        if (player != null && player.isPlaying()) {
            player.pause();
            sendCustomerNotification(CommandPause,music);
            //iv_play.setSelected(false);
        }
    }

    public boolean isPlaying() {
        return player != null && player.isPlaying();
    }
    //---------------------歌曲播放控制部分 结束---------------------------------------

    //command是自定义用来区分各种点击事件的
    private void sendCustomerNotification(int command,Music music) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this,channelId);
        builder.setContentTitle("Notification");
        builder.setContentText("自定义通知栏示例");
        builder.setSmallIcon(R.mipmap.ic_launcher);
        //builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.push))
        builder.setAutoCancel(false);
        builder.setOngoing(true);
        builder.setShowWhen(false);
        //如果使用自定义布局，就需要使用RemoteViews
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification_music);
        remoteViews.setTextViewText(R.id.tv_name, "我的播放器");
        remoteViews.setTextViewText(R.id.tv_artist, music.getTitle() + " 正在播放");
        if (command == CommandPlay) {
            remoteViews.setImageViewResource(R.id.iv_play, R.drawable.ic_pause);
        } else if (command == CommandPause) {
            remoteViews.setImageViewResource(R.id.iv_play, R.drawable.ic_play);
        }
        //-----------------------
        Intent Intent1 = new Intent(this, PlayService.class);
        Intent1.putExtra("command", command);
        //PendingIntent: 将来、准备干什么
        PendingIntent PIntent1 = PendingIntent.getService(this, 5, Intent1, 0);
        remoteViews.setOnClickPendingIntent(R.id.iv_play, PIntent1);
        //------------------------
        Intent Intent2 = new Intent(this, PlayService.class);
        Intent2.putExtra("command", CommandNext);
        PendingIntent PIntent2 = PendingIntent.getService(this, 6, Intent2, 0);
        remoteViews.setOnClickPendingIntent(R.id.iv_next, PIntent2);

        Intent Intent3 = new Intent(this, PlayService.class);
        Intent3.putExtra("command", CommandClose);
        PendingIntent PIntent3 = PendingIntent.getService(this, 7, Intent3, 0);
        remoteViews.setOnClickPendingIntent(R.id.iv_close, PIntent3);
        //设置自定义的布局
        builder.setContent(remoteViews);
        Notification notification = builder.build();//建立通知
        manager.notify(11, notification);//发送通知
        //通知发送出去以后，无法和通知建立联系的
        //修改通知：再次发送通知来实现
    }
}
